package qw

import (
	"encoding/json"
	"errors"
	"log/slog"
	"net/url"
)

// SendMessage 应用支持推送文本、图片、视频、文件、图文等类型。
func (w *QYWXApi) SendMessage(param map[string]any) (string, error) {
	accessToken, err := w.GetAccessToken()
	if err != nil {
		return "", err
	}

	var values = url.Values{}
	values.Add("access_token", accessToken)
	reqUrl := "https://qyapi.weixin.qq.com/cgi-bin/message/send?" + values.Encode()

	data, _ := json.Marshal(param)
	slog.Debug("sendMessage", "requestData", string(data))

	res, err := w.getHttpSvc().HttpPost(reqUrl, nil, data)
	if err != nil {
		slog.Error(err.Error())
		return "", err
	}
	slog.Debug("sendMessage", "responseData", string(res.Body))

	type Result struct {
		Errcode      int    `json:"errcode"`
		Errmsg       string `json:"errmsg"`
		MsgId        string `json:"msgid"`
		ResponseCode string `json:"response_code"`
	}

	var result Result
	if err := json.Unmarshal(res.Body, &result); err != nil {
		slog.Error(err.Error())
		return "", err
	}
	if result.Errcode != 0 {
		return "", errors.New("发送消息失败，返回结果：" + string(res.Body))
	}
	return result.MsgId, nil
}

// SendMessageText 文本消息
// toUser指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个），特殊情况：指定为”@all”，则向该企业应用的全部成员发送
func (w *QYWXApi) SendMessageText(agentId int64, toUser, content string) (string, error) {
	var param = map[string]any{
		"touser":  toUser,
		"msgtype": "text",
		"agentid": agentId,
		"text": map[string]any{
			"content": content,
		},
		"safe":                     0,
		"enable_id_trans":          0,
		"enable_duplicate_check":   0,
		"duplicate_check_interval": 1800,
	}
	return w.SendMessage(param)
}

// SendMessageTextCard 文本卡片消息
// toUser指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个），特殊情况：指定为”@all”，则向该企业应用的全部成员发送
func (w *QYWXApi) SendMessageTextCard(agentId int64, toUser, title, description, btnUrl, btnTxt string) (string, error) {
	var param = map[string]any{
		"touser":  toUser,
		"msgtype": "textcard",
		"agentid": agentId,
		"textcard": map[string]any{
			"title":       title,
			"description": description,
			"url":         btnUrl,
			"btntxt":      btnTxt,
		},
		"safe":                     0,
		"enable_id_trans":          0,
		"enable_duplicate_check":   0,
		"duplicate_check_interval": 1800,
	}
	return w.SendMessage(param)
}
